// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;

import GlobalData from './GlobalData'

const { TOUCH_START } = cc.Node.EventType

@ccclass
export default class GameRoot extends cc.Component {

    @property(cc.Node)
    ropNode: cc.Node = null; // 套绳节点

    @property(cc.Node)
    cowIns: cc.Node = null; // 牛儿节点
    
    @property([cc.SpriteFrame])
    cowRopImgs: cc.SpriteFrame[] = []; // 套绳图集

    @property
    ropNum: number = 60; // 套绳数量

    @property(cc.AudioClip)
    ropBtnAudio: cc.AudioClip = null;


    scoreNum: number = 0; // 分数

    // 定时器
    maxTimer: number = 60;
    currentTimer: number = 0;
    coutDownNodeLabel: cc.Label = null;

    // 称号
    titleNames = [
        {
            score: 5,
            name: '青铜'
        },
        {
            score: 10,
            name: '白银'
        },
        {
            score: 15,
            name: '黄金'
        },
        {
            score: 20,
            name: '铂金'
        },
        {
            score: 25,
            name: '钻石'
        },
        {
            score: 30,
            name: '星耀'
        },
        {
            score: 35,
            name: '王者'
        }
    ]

    isRoupRuning: boolean = false; // 套装是否已经扔出去了

    gameState: number = 0; // 游戏状态 0初始化，1结束

    levelNum: number = 1; // 关卡

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.ropNode.y = -600;
        this.ropNode.setSiblingIndex(100);

        // cc.game.addPersistRootNode(this.node)

        this.ropNum += GlobalData.ropNum;
        this.scoreNum += GlobalData.money;
        this.node.getChildByName('score').getComponent(cc.Label).string = 'Money: ' + this.scoreNum;
    }

    start () {
        // this.coutDownHandler();
        this.updateRopNum();
    }

    // update (dt) {}

    /**
     *  捕获按钮点击事件
     * @param event
     * @param customEventDate
     */
    clickCapture(){
        cc.audioEngine.play(this.ropBtnAudio, false, 1)
        if(this.isRoupRuning && this.gameState !== 1){
            return
        }
        this.isRoupRuning = true;
        cc.tween(this.ropNode)
            .to(0.5, {position: cc.v3(0, 50, 0)})
            .call(() => {
                
                let {cowDifficulty, currentCowType, cowRun, money} = this.getCowParams();

                const x = this.cowIns.x;
                
                if((x < cowDifficulty) && (x > -cowDifficulty) ){
                    // cc.log('成功')
                    if(cowRun && cowRun.rePlayRun){
                        cowRun.rePlayRun() // 重置牛儿皮肤和运动
                    }

                    this.updateRoupSkin(currentCowType)

                    this.scoreNum += money;
                    this.node.getChildByName('score').getComponent(cc.Label).string = 'Money: ' + this.scoreNum;

                    if(cowRun && cowRun.changeSpeed){
                        cowRun.changeSpeed(this.scoreNum) // 根据分数值，加快速度，怎加难度
                    }
                }else{
                    // cc.log('失败')
                }
                
                this.ropNum--; // 每套中一头牛消耗一根套绳
                this.updateRopNum();
            })
            .to(0.5, {position: cc.v3(0, -600, 0)})
            .call(() => {
                this.updateRoupSkin(0)
                this.isRoupRuning = false;

                if(this.ropNum <= 0){
                    this.gameOverHandler(); // 套绳用完则游戏介绍
                }
            })
            .start()
    }

    // 获取相关参数
    getCowParams(){
        let cowDifficulty: number = 100; // 不同的牛难度不一样
        let currentCowType: number = 0; // 当前牛的类型
        let money: number = 0;
        const cowRun = this.cowIns.getComponent('CowRun');

        const cowscript = cowRun.currentSkin;
        
        if(cowscript){
            cowDifficulty = cowscript.cowDifficulty
            currentCowType = cowRun.cowType + 1
            money = cowscript.cowPrice
        }
        
        return {
            cowDifficulty,
            currentCowType,
            cowRun,
            money
        }
    }

    // 更新套绳皮肤
    updateRoupSkin(num: number){
        this.ropNode.getComponent(cc.Sprite).spriteFrame = this.cowRopImgs[num];
    }

    // 更新套绳数量
    updateRopNum(){
        if(!this.coutDownNodeLabel){
            this.coutDownNodeLabel = this.node.getChildByName('timerNum').getComponent(cc.Label)
        }
        // cc.log(this.ropNum)
        this.coutDownNodeLabel.string = '套绳: ' + this.ropNum;
    }

    /**
     * 倒计时
     */
    coutDownHandler(){
        this.currentTimer = this.maxTimer;
        if(!this.coutDownNodeLabel){
            this.coutDownNodeLabel = this.node.getChildByName('timerNum').getComponent(cc.Label)
        }
        this.coutDownNodeLabel.string = this.currentTimer + 's';
        // this.schedule(this.coutDownHandlerCallback, 1)
    }
    coutDownHandlerCallback(){
        if(!this.coutDownNodeLabel){
            cc.log('no this.coutDownNodeLabel')
            return
        }
        this.currentTimer--;
        this.coutDownNodeLabel.string = this.currentTimer + 's';
        if(this.currentTimer <= 0){
            this.unschedule(this.coutDownHandlerCallback)

            this.gameOverHandler()
        }
    }

    // 游戏结束
    gameOverHandler(){
        const resultNode = this.node.getChildByName('result')
        resultNode.setSiblingIndex(110)
        // const titleNode = resultNode.getChildByName('title');
        // titleNode.getComponent(cc.Label).string = `获得金币: ${this.scoreNum}`
        const titleNameNode = resultNode.getChildByName('titleName')
        const nameobj = this.titleNames.find(item => item.score > this.scoreNum) || this.titleNames[this.titleNames.length - 1]
        titleNameNode.getComponent(cc.Label).string = `获得称号：${nameobj.name}`
        resultNode.active = true;

        cc.director.pause() // 停止游戏
    }

    // 继续游戏
    nextGame(){
        
        if(this.scoreNum <= 0){
            cc.find('Canvas/result/tip').opacity = 255;
            return
        }
        this.ropNum += this.scoreNum;
        this.scoreNum = 0;
        this.node.getChildByName('score').getComponent(cc.Label).string = 'Money: ' + this.scoreNum;
        this.coutDownNodeLabel.string = '套绳: ' + this.ropNum;

        const resultNode = this.node.getChildByName('result')
        resultNode.active = false;
        // this.coutDownHandler()
        this.levelNum++;
        // this.titleNames = this.titleNames.map(item => {
        //     return {
        //         ...item,
        //         score: item.score + Math.ceil(this.scoreNum / 2) + this.levelNum // 每次关卡升级后，等级分数要随之增加
        //     }
        // })
        cc.director.resume()
    }

    goShopSence(){
        GlobalData.ropNum = this.ropNum;
        GlobalData.money = this.scoreNum;
        cc.director.loadScene('shop')
        // cc.find('Canvas/shop').active = true;
    }

    // 重新开始
    reloadGame(){
        cc.director.resume()
        cc.director.loadScene('main')
    }
}
